/**
 *
 */
// 涉及的表名
const dbName = require("../config.js");

var dao = {};
var util = {};
// 初始化
dao.init = function(obj) {
	util = obj;
}
/**
 * 查 - 根据id获取单条记录
 * @params {String} id
 * @params {Object} fieldJson 字段显示规则
 * 调用示例
 * let userGoodsPerInfo = await vk.daoCenter.userGoodsPerDao.findById(id);
 */
dao.findById = async (id, fieldJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.findById({
		dbName: dbName.userGoodsPer,
		id,
		fieldJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};
/**
 * 查 - 根据whereJson获取单条记录
 * @params {Object} whereJson 条件
 * @params {Object} fieldJson 字段显示规则
 * 调用示例
let userGoodsPerInfo = await vk.daoCenter.userGoodsPerDao.findByWhereJson({

});
 */
dao.findByWhereJson = async (whereJson, fieldJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.findByWhereJson({
		dbName: dbName.userGoodsPer,
		whereJson,
		fieldJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 增 - 添加一条记录
 * @params {Object} dataJson 添加的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.add({

});
 */
dao.add = async (dataJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.add({
		dbName: dbName.userGoodsPer,
		dataJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 增 - 添加多条记录
 * @params {Object} dataJson 添加的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.adds(dataArr);
 */
dao.adds = async (dataArr) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.adds({
		dbName: dbName.userGoodsPer,
		dataJson: dataArr
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 删 - 删除多条记录
 * @params {Object} whereJson 条件
 * 调用示例
await vk.daoCenter.userGoodsPerDao.del({

});
 */
dao.del = async (whereJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.del({
		dbName: dbName.userGoodsPer,
		whereJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 删 - 据ID删除单条数据
 * @params {String} id
 * 调用示例
await vk.daoCenter.userGoodsPerDao.deleteById(id);
 */
dao.deleteById = async (id) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.deleteById({
		dbName: dbName.userGoodsPer,
		id
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 改 - 批量修改
 * @params {Object} whereJson 条件
 * @params {Object} dataJson 修改的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.update({
	whereJson:{

	},
	dataJson:{

	}
});
 */
dao.update = async (obj = {}) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.update({
		...obj,
		dbName: dbName.userGoodsPer,
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 改 - 根据ID修改数据
 * @params {String} id
 * @params {Object} dataJson 修改的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.updateById(id, dataJson);
 */
dao.updateById = async (id, dataJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.updateById({
		dbName: dbName.userGoodsPer,
		id,
		dataJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 改 - 更新并返回更新后的数据（无论条件匹配到多少条记录，只会修改第一条记录，同时返回修改后的数据）
 * @params {Object} whereJson 条件
 * @params {Object} dataJson 修改的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.updateAndReturn({
	whereJson:{

	},
	dataJson:{

	}
});
 */
dao.updateAndReturn = async (obj = {}) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.updateAndReturn({
		...obj,
		dbName: dbName.userGoodsPer
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 查 - 获取记录总条数
 * @params {Object} whereJson 条件
 * 调用示例
await vk.daoCenter.userGoodsPerDao.count(whereJson);
 */
dao.count = async (whereJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.count({
		dbName: dbName.userGoodsPer,
		whereJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 查 - 根据id获取单条记录
 * @params {String} fieldName 需要求和的字段名
 * @params {Object} whereJson 筛选条件
 * 调用示例
let userGoodsPerSum = await vk.daoCenter.userGoodsPerDao.sum({
	fieldName: "",
	whereJson: {

	}
});
 */
dao.sum = async (obj) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.sum({
		...obj,
		dbName: dbName.userGoodsPer,
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};


/**
 * 查 - 获取数据列表
 * 调用示例
let userGoodsPerList = await vk.daoCenter.userGoodsPerDao.select({
	pageIndex:1,
	pageSize:20,
	getMain:false,
	whereJson:{

	},
	fieldJson:{},
	sortArr:[{ "name":"_id", "type":"desc" }],
});
 */
dao.select = async (obj = {}) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.select({
		...obj,
		dbName: dbName.userGoodsPer
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 查 - 获取数据列表
 * 调用示例
let userGoodsPerList = await vk.daoCenter.userGoodsPerDao.selects({
	pageIndex:1,
	pageSize:20,
	getMain:false,
	whereJson:{

	},
	fieldJson:{},
	sortArr:[{ "name":"_id", "type":"desc" }],
	// 副表列表
	foreignDB:[
		{
			dbName:"副表表名",
			localKey:"主表外键名",
			foreignKey:"副表外键名",
			as:"副表as字段",
			limit:1
		}
	]
});
 */
dao.selects = async (obj = {}) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.selects({
		...obj,
		dbName: dbName.userGoodsPer
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 查 - 获取数据列表
 * 调用示例
res = await vk.daoCenter.userGoodsPerDao.getTableData({
	data
});
 */
dao.getTableData = async (obj = {}) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.getTableData({
		...obj,
		dbName: dbName.userGoodsPer
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};



/**
 * 增 - 根据订单添加商品业绩
 * @params {Object} dataJson 添加的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.addByOrder({

});
 */
dao.addByOrder = async (obj = {}) => {
	let { vk, _ } = util;
	let res = { code: 0, msg: "" };
	let {
		db,
		orderInfo,
		userInfo
	} = obj;
	// 数据库操作开始-----------------------------------------------------------
	let { goods_sku_list } = orderInfo;
	let { now } = vk.pubfn.getCommonTime(new Date());
	let { now: now2 } = vk.pubfn.getCommonTime(orderInfo.pay_time);
	let cashK = orderInfo.amount_info.used_cash_amount / orderInfo.amount_info.payment_amount; // 现金比例
	if (orderInfo.amount_info.payment_amount == 0) {
		cashK = 0;
	}
	for (let i = 0; i < goods_sku_list.length; i++) {
		let goodsItem = goods_sku_list[i];
		let goods_cash_amount = vk.pubfn.toDecimal(goodsItem.should_payment_amount * cashK, 0);
		if (goodsItem.should_payment_amount > 0) {
			await vk.baseDao.add({
				db,
				dbName: dbName.userGoodsPer,
				dataJson: {
					user_id: userInfo._id,
					inviter_uid: userInfo.inviter_uid,
					nickname: userInfo.nickname,
					title: `【${userInfo.nickname}】【购买】商品：${goodsItem.goods_name} * ${goodsItem.buy_num}`,
					comment: ``,
					goods_id: goodsItem.goods_id,
					goods_name: goodsItem.goods_name,
					image: goodsItem.image,
					sku_id: goodsItem._id,
					sku_name: goodsItem.sku_name,
					buy_num: goodsItem.buy_num,
					refund_num: 0,
					no: orderInfo.order_no,
					add_type: 7, // 标记业绩是奖励发放产生的，当退款时需要反向扣除
					amount: {
						goods_original_amount: goodsItem.total_amount,
						goods_payment_amount: goodsItem.should_payment_amount,
						goods_cash_amount: goods_cash_amount,
						recharge_cash_amount: 0,
						cash_amount: goods_cash_amount
					},
					pay_time: orderInfo.pay_time,
					pay_time_date: now2,
					date: now,
				}
			});
		}
	}
	await vk.daoCenter.userDao.updateById({
		db,
		id: userInfo._id,
		dataJson: {
			"account_per.my_payment": _.inc(orderInfo.amount_info.payment_amount)
		}
	});
	console.log(`${userInfo._id}（${userInfo.nickname}）【业绩】【增加】${ vk.pubfn.toDecimal(orderInfo.amount_info.payment_amount / 100, 2)}`)
	// 数据库操作结束-----------------------------------------------------------
	return res;
};


/**
 * 增 - 根据订单添加商品业绩
 * @params {Object} dataJson 添加的数据
 * 调用示例
await vk.daoCenter.userGoodsPerDao.addByRefundOrder({

});
 */
dao.addByRefundOrder = async (obj = {}) => {
	let { vk, _ } = util;
	let res = { code: 0, msg: "" };
	let {
		db,
		refundInfo, // 退款单信息
		userInfo, // 用户信息
		orderInfo, // 订单信息
	} = obj;
	// 数据库操作开始-----------------------------------------------------------
	let {
		order_no, // 订单号
	} = orderInfo;
	// 获取本次退款的商品信息（数量）
	let {
		goods_list: refund_goods_list, // 退款商品列表
		refund_amount: total_refund_amount, // 退款金额
	} = refundInfo;
	// 存放最终扣除业绩的列表
	let usersPerList = [];
	// 查询该订单产生的业绩记录
	let goodsPerList = await vk.daoCenter.userGoodsPerDao.listByNo({
		no: order_no,
		add_type: 7
	});
	let time = Date.now();
	let { now } = vk.pubfn.getCommonTime(new Date());
	// 循环商品业绩列表
	for (let i = 0; i < goodsPerList.length; i++) {
		let goodsPerItem = goodsPerList[i];
		let { sku_id, buy_num } = goodsPerItem;
		// 需要扣除的业绩 = 该商品退款金额/ 商品付款金额 * 该商品对应产生的业绩
		// 获取本次退款金额和退款数量
		let refundGoodsItem = vk.pubfn.getListItem(refund_goods_list, "sku_id", sku_id);
		if (!refundGoodsItem) {
			continue;
		}
		let { refund_num } = refundGoodsItem;
		// 退款商品占比 = 退款金额 / 付款金额
		let amountK = refundGoodsItem.refund_amount / refundGoodsItem.payment_amount;
		let amount = {};
		// 循环业绩数据，并 * -1
		for (let key in goodsPerItem.amount) {
			if (key.indexOf("_amount") > -1) {
				amount[`refund_${key}`] = vk.pubfn.toDecimal(goodsPerItem.amount[key] * amountK * -1, 0);
			}
		}
		await vk.baseDao.add({
			db,
			dbName: dbName.userGoodsPer,
			dataJson: {
				user_id: goodsPerItem.user_id,
				inviter_uid: goodsPerItem.inviter_uid,
				nickname: goodsPerItem.nickname,
				title: `【${goodsPerItem.nickname}】【退款】商品：${goodsPerItem.goods_name} * ${refund_num}`,
				comment: ``,
				goods_id: goodsPerItem.goods_id,
				goods_name: goodsPerItem.goods_name,
				image: goodsPerItem.image,
				sku_id: goodsPerItem.sku_id,
				sku_name: goodsPerItem.sku_name,
				refund_num: vk.pubfn.toDecimal(refund_num * -1, 0),
				no: order_no,
				add_type: 4, // 1 人工录入 2 用户线上充值 3 消费 4 退款 5 转账 6 余额转换 7 奖励发放 8 解锁 9 提现 10 提现拒绝后返还
				amount,
				pay_time: goodsPerItem.pay_time,
				pay_time_date: goodsPerItem.pay_time_date,
				refund_time: orderInfo.refund_time,
				date: now
			}
		});
	}
	let my_payment_inc = vk.pubfn.toDecimal(total_refund_amount * -1, 0);
	await vk.daoCenter.userDao.updateById({
		db,
		id: userInfo._id,
		dataJson: {
			"account_per.my_payment": _.inc(my_payment_inc)
		}
	});
	console.log(`${userInfo._id}（${userInfo.nickname}）【业绩】【减少】${ vk.pubfn.toDecimal(total_refund_amount / 100, 2)}`)
	// 数据库操作结束-----------------------------------------------------------
	return res;
};


/**
 * 查 - 根据订单号查询
 * 调用示例
let goodsPerList = await vk.daoCenter.userGoodsPerDao.listByNo({
	no: order_no,
});
 */
dao.listByNo = async (whereJson) => {
	let { vk, db, _ } = util;
	let res = {};
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.select({
		dbName: dbName.userGoodsPer,
		getCount: false,
		getMain: true,
		pageIndex: 1,
		pageSize: 500,
		whereJson
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};


/**
 * 查 - 获取业绩
 * 调用示例
await vk.daoCenter.userGoodsPerDao.sumPer({
	whereJson:{

	}
});
 */
dao.sumPer = async (obj = {}) => {
	let { vk, db, _ } = util;
	let res = {};
	let {
		whereJson
	} = obj;
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.baseDao.selects({
		dbName: dbName.userGoodsPer,
		getMain: true,
		getOne: true,
		// 主表where条件
		whereJson,
		groupJson: {
			_id: null, // _id是分组id， $ 后面接字段名，如user_id字段进行分组
			goods_payment_amount: _.$.sum("$amount.goods_payment_amount"),
			refund_goods_payment_amount: _.$.sum("$amount.refund_goods_payment_amount"),
			calc_goods_payment_amount: _.$.sum(_.$.sum(["$amount.goods_payment_amount", "$amount.refund_goods_payment_amount"])),
		}
	});
	if (!res) {
		res = {
			goods_payment_amount:0,
			refund_goods_payment_amount:0,
			calc_goods_payment_amount:0
		};
	}
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 查 - 获取指定的直推业绩
 * 调用示例
let per1 = await vk.daoCenter.userGoodsPerDao.sumShare1PerByUserId({
	user_id: uid
});
 */
dao.sumShare1PerByUserId = async (obj={}) => {
	let { vk, db, _ } = util;
	let res = {};
	let {
		user_id = "___"
	} = obj;
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.daoCenter.userGoodsPerDao.sumPer({
		whereJson:{
			["inviter_uid.0"]: user_id
		}
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};

/**
 * 查 - 获取指定的团队业绩
 * 调用示例
let per2 = await vk.daoCenter.userGoodsPerDao.sumShare12PerByUserId({
	user_id: uid
});
 */
dao.sumShare12PerByUserId = async (obj={}) => {
	let { vk, db, _ } = util;
	let res = {};
	let {
		user_id = "___"
	} = obj;
	// 数据库操作开始-----------------------------------------------------------
	res = await vk.daoCenter.userGoodsPerDao.sumPer({
		whereJson: _.or([
			{
				["inviter_uid.0"]: user_id
			},
			{
				["inviter_uid.1"]: user_id
			}
		])
	});
	// 数据库操作结束-----------------------------------------------------------
	return res;
};



module.exports = dao;
